var redis = require("./RedisUtils");
var http = require("http");
var https = require("https");
var queryString=require('querystring');
var config = require("../conf/config")

var menuList = redis.get("manager",function (data) {
    console.log(data);
    menuList = data;
});

exports.menus = function (req,menuName) {

    console.log(JSON.stringify(menuList));

    switch(req.session.proName){
        case "manager":
            console.log(menuList[menuName]["method"]);
            return menuList[menuName]["method"];
            break;
        default:
            return null;
    }
}

exports.urls = function (req,urlName,cb) {
    switch (req.session.proName){
        case "manager":
            console.log(menuList[urlName]["url"]);
            cb(menuList[urlName]["name"],menuList[urlName]["url"])
            break;
        default:
            return null;
    }
}

exports.render = function (req,res,urlName,options) {
    if((req.session.userid == "" || req.session.userid == undefined) && menuList[urlName]["isLogin"] == 1){
        this.urls(req,'login',function (name,url) {
            var param = {
                title:name
            };
            res.render(url,param);
        });
    }
    this.urls(req,urlName,function (name,url) {
        var param = {title:name,
            menus:req.session.menus,
            userName:req.session.userName
        };
        if(options){
            Object.assign(param,options);
        }
        res.render(url,param)
    });
}

exports.httpPost = function (method,data,cb) {
    var postData = queryString.stringify(data);
    var options = {
        hostname:config["hostname"],
        port:config["serverPort"],
        path:method,
        method:"POST",
        headers:{
            'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8',
            'Content-Length':Buffer.byteLength(postData)
        }
    }

    var req=http.request(options, function(res) {
        console.log('Status:',res.statusCode);
        console.log('headers:',JSON.stringify(res.headers));
        res.setEncoding('utf-8');
        res.on('data',function(chun){
            console.log('body分隔线---------------------------------\r\n');
            console.info(chun);
            if(res.statusCode == 200){
                cb(JSON.parse(chun));
            }else {
                cb({code:res.statusCode})
            }

        });
        res.on('end',function(){
            console.log('No more data in response.********');
        });
    });
    req.on('error',function(err){
        console.error(err);
    });
    req.write(postData);
    req.end();
}